package org.jeecg.modules.engineer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.RedisPublicKeyPrefixConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.engineer.entity.MtEngineer;
import org.jeecg.modules.engineer.mapper.MtEngineerMapper;
import org.jeecg.modules.engineer.service.IMtEngineerService;
import org.jeecg.modules.order.service.IMtRepairOrderService;
import org.jeecg.modules.providers.entity.MtServiceProviders;
import org.jeecg.modules.providers.service.IMtServiceProvidersService;
import org.jeecg.modules.station.entity.MtServiceStation;
import org.jeecg.modules.station.service.IMtServiceStationService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description: 工程师表
 * @Author: jeecg-boot
 * @Date: 2022-08-16
 * @Version: V1.0
 */
@Service
public class MtEngineerServiceImpl extends ServiceImpl<MtEngineerMapper, MtEngineer> implements IMtEngineerService {

    private final RedisUtil redisUtil;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private IMtRepairOrderService mtRepairOrderService;
    @Autowired
    private IMtServiceProvidersService mtServiceProvidersService;
    @Autowired
    private IMtServiceStationService mtServiceStationService;

    public MtEngineerServiceImpl(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEngineerAndCreateUser(MtEngineer mtEngineer) {
        JSONObject user = new JSONObject();
        user.put("username", mtEngineer.getEngineerMobile());//账号：工程师手机号
        user.put("realname", mtEngineer.getEngineerName());//用户名称：工程师名称
        user.put("password", mtEngineer.getEngineerMobile());//密码：工程师手机号
        user.put("phone", mtEngineer.getEngineerMobile());//手机号
        user.put("confirmpassword", mtEngineer.getEngineerMobile());
        user.put("useridentity", 1);//身份（1 普通成员 2 上级）
        user.put("userId", mtEngineer.getEngineerMobile());
        user.put("activitisync", 1);//同步工作流引擎(1-同步,0-不同步)
        user.put("contacts", mtEngineer.getEngineerName());//联系人
        user.put("workNo", mtEngineer.getEngineerMobile());//工号：手机号码
        user.put("usertype", 3);//0平台管理员 1服务商 2服务站 3工程师 4客户
        //插入到user表中，并设置角色
        Result<SysUser> userResult = sysUserService.addUserAndRole(user);
        redisUtil.removeAll(CacheConstant.SYS_DEPARTS_CACHE);
        redisUtil.removeAll(CacheConstant.SYS_DEPART_IDS_CACHE);
        if (!userResult.isSuccess()) {
            //报错，进行事务回滚
            throw new JeecgBootException(userResult.getMessage());
        }
        // 获取工作站orgCode
        MtServiceStation station = mtServiceStationService.getById(mtEngineer.getStationId());
        SysUser result = userResult.getResult();
        mtEngineer.setUserId(result.getUsername()) //账号绑定
                .setSysOrgCode(station.getSysOrgCode());//工作站orgCode
        super.save(mtEngineer);
        // 更新用户关联id
        SysUser sysUser = new SysUser();
        sysUser.setId(result.getId())
                .setLinkId(mtEngineer.getId());
        sysUserService.updateById(sysUser);
        String jsonString = JSON.toJSONString(mtEngineer);
        redisUtil.set(RedisPublicKeyPrefixConstant.ENGINEER + ":" + mtEngineer.getSysOrgCode() + ":" + mtEngineer.getCreateBy(), jsonString, 60 * 60 * 2);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeEngineerAndUserRole(String id) {
        //首先判断该工程师手里有没有未完成的单子，有的话，就删除不了
        MtEngineer engineer1 = super.getById(id);
        //TODO 根据工程师id去工单表中查数据，

        super.removeById(id);
        //根据工程师电话查找出在系统中的信息
        MtEngineer engineer = super.getById(id);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getPhone, engineer.getEngineerMobile());
        SysUser one = sysUserService.getOne(queryWrapper);
        //判断不为空，就进行user表中的删除
        if (!ObjectUtil.isEmpty(one)) {
            sysUserService.deleteUser(one.getId());

            //根据查出来的系统用户，查询角色，并删除中间表中的角色对应关系
            LambdaQueryWrapper<SysUserRole> query = new LambdaQueryWrapper<>();
            query.eq(SysUserRole::getUserId, one.getId());
            sysUserRoleService.remove(query);
        }

    }

    @Override
    @Transactional
    public void removeEngineersAndUserRolesByIds(List<String> asList) {
        //先删除engineer表中的数据
        super.removeByIds(asList);
        //删除user表中的数据
        for (String id : asList) {
            //现根据工程师id查出工程师所有信息
            MtEngineer engineer = super.getById(id);
            //根据工程师电话，对比user表中的电话，删除user表中对应的数据
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getPhone, engineer.getEngineerMobile());
            SysUser one = sysUserService.getOne(queryWrapper);
            sysUserService.deleteUser(one.getId());

            //删除user_role表中的数据
            LambdaQueryWrapper<SysUserRole> query = new LambdaQueryWrapper<>();
            query.eq(SysUserRole::getUserId, one.getId());
        }

    }
}
